<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/20 23:13
 */

namespace module\chat\controller;

use module\chat\logic\UnlimitedLogic;
use module\user\library\UserController;
use mof\ApiResponse;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\response\Json;

class Unlimited extends UserController
{

    public function __construct(App $app, protected UnlimitedLogic $logic)
    {
        parent::__construct($app);
        $this->logic->withUser($this->auth->getUser());
    }

    /**
     * 获取会话列表
     * @return Json
     */
    public function index(): Json
    {
        return ApiResponse::success($this->logic->list());
    }

    /**
     * 会话内容
     * @param $id
     * @return Json
     * @throws DataNotFoundException
     */
    public function read($id): Json
    {
        $model = $this->logic->withAccess(['user_id' => $this->auth->getId()])->read($id);
        return ApiResponse::success($model);
    }

    /**
     * 新建对话
     * @param string $name 会话名称
     * @return Json
     * @throws DbException
     */
    public function save(string $name = '新的对话'): Json
    {
        return ApiResponse::success(
            $this->logic->save(['user_id' => $this->auth->getId(), 'name' => $name])
        );
    }

    /**
     * 重命名会话名称
     * @param integer $id 会话ID
     * @param string $name 新名称
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function update(int $id, string $name): Json
    {
        return ApiResponse::success(
            $this->logic
                ->withAccess(['user_id' => $this->auth->getId()])
                ->update($id, ['name' => $name])
        );
    }

    /**
     * 删除
     * @param int $id
     * @return Json
     * @throws DataNotFoundException
     */
    public function delete(int $id): Json
    {
        $this->logic->withAccess(['user_id' => $this->auth->getId()])->delete($id);
        return ApiResponse::success();
    }

}